package com.itheima.stock.service.impl;

import com.google.common.base.Strings;
import com.itheima.stock.mapper.SysUserMapper;
import com.itheima.stock.pojo.SysUser;
import com.itheima.stock.service.UserService;
import com.itheima.stock.utils.IdWorker;
import com.itheima.stock.vo.req.LoginReqVo;
import com.itheima.stock.vo.resp.LoginRespVo;
import com.itheima.stock.vo.resp.R;
import com.itheima.stock.vo.resp.ResponseCode;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private SysUserMapper sysUserMapper;

    //密码匹配器
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 分布式环境保证生成id唯一
     */
    @Autowired
    private IdWorker idWorker;

    /**
     * 登录
     *
     * @param vo 签证官
     * @return {@link R}<{@link LoginRespVo}>
     */
    @Override
    public R<LoginRespVo> login(LoginReqVo vo) {
        //判断传过来的用户名和密码参数是否合法
        boolean b1 = Strings.isNullOrEmpty(vo.getUsername()) || Strings.isNullOrEmpty(vo.getPassword());
        //判断验证码的参数是否合法
        boolean b2 = Strings.isNullOrEmpty(vo.getRkey()) || Strings.isNullOrEmpty(vo.getCode());
        if (vo==null||b1||b2){
            return R.error(ResponseCode.SYSTEM_PASSWORD_ERROR .getMessage());
        }
        //验证码校验
        //获取redis中rkey对应的code验证码
        String rCode = (String) redisTemplate.opsForValue().get("ck:"+vo.getRkey());
        if (rCode==null||!rCode.equals(vo.getCode())){
            return R.error(ResponseCode.SYSTEM_VERIFY_CODE_ERROR.getMessage());
        }
        //redis清除key
        redisTemplate.delete("ck:"+vo.getRkey());
        //根据用户名查询用户信息
        String username = vo.getUsername();
        SysUser info = sysUserMapper.getUserInfoByUserName(username);
        //判断查询的用户信息
        if (info==null){
            return R.error(ResponseCode.SYSTEM_PASSWORD_ERROR.getMessage());
        }
        //判断输入的密码与数据库的密文密码进行匹配
        boolean bool = passwordEncoder.matches(vo.getPassword(), info.getPassword());
        if (!bool){
            return R.error(ResponseCode.SYSTEM_PASSWORD_ERROR.getMessage());
        }
        LoginRespVo loginRespVo = new LoginRespVo();
        BeanUtils.copyProperties(info,loginRespVo);

        return R.ok(loginRespVo);
        //TODO:用户登录成功动态回显菜单栏功能

    }

    /**
     * 获取验证码
     *
     * @return {@link R}<{@link Map}>
     */
    @Override
    public R<Map> getCaptcha() {
        //1.生成4位数字验证码
        String checkCode = RandomStringUtils.randomNumeric(4);
        //2.获取全局唯一id
        String rkey=String.valueOf(idWorker.nextId());
        //验证码存入redis中，并设置有效期1分钟
        redisTemplate.opsForValue().set("ck:"+rkey,checkCode,60, TimeUnit.SECONDS);
        //3.组装数据
        HashMap<String, String> map = new HashMap<>();
        map.put("rkey",rkey);
        map.put("code",checkCode);
        return R.ok(map);
    }
}
